package cn.com.unionlife.hy.system.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.com.unionlife.hy.core.controller.BaseController;
import cn.com.unionlife.hy.core.exception.BusinessException;
import cn.com.unionlife.hy.core.utils.MD5Utils;
import cn.com.unionlife.hy.system.service.UserQryService;
import cn.com.unionlife.hy.system.vo.UserVO;

import com.ulic.um.client.UMContext;
import com.ulic.um.client.UMUser;

@Controller("loginController")
public class LoginController extends BaseController {
	
	@Resource(name = "userQryService")
	private UserQryService userQryService;

	@RequestMapping(value = "/login" , method=RequestMethod.POST)
	public String doLogin(@RequestParam("username")String username , @RequestParam("password")String passwod , HttpServletRequest request , Model model) throws BusinessException{
		StringBuilder msg = new StringBuilder();
		if(username != null && !"".equals(username)){
			UserVO loginUser = userQryService.getUserByUsername(username);
			if(loginUser == null){
				msg.append("用户名或密码不正确");
			}else{
				String md5Pwd = MD5Utils.getMD5Digest(passwod);
				if(!StringUtils.equals(loginUser.getPassword(), md5Pwd)){
					msg.append("用户名或密码不正确");
				}else{
					request.getSession(true).setAttribute(LOGINED_USER, loginUser);
				}
			}
		}else{
			msg.append("请输入用户名");
		}
		
		if(msg.length() > 0){
			model.addAttribute("msg" , msg.toString());
			return "system/login";
		}
		return "redirect:/home";
	}
	
	@RequestMapping(value = "/caslogin")
	public String casLogin(HttpServletRequest request) throws BusinessException{
		
		StringBuilder msg = new StringBuilder();
		UMUser  umUser = UMContext.getCurrentUser();
		
		if(umUser !=null){
			UserVO loginedUser = userQryService.getUserById(umUser.getUlicUMUserID());
			if(loginedUser!=null){
				if(loginedUser.isEnabled()){
					request.getSession(true).setAttribute(LOGINED_USER, loginedUser);
					return "redirect:/home";
				}else{
					msg.append("该用户未启用，请联系管理员！");
				}
			}else{
				msg.append("登录错误");
			}
		}else{
			msg.append("登录错误");
		}
		return "system/login";
	}
	
	@RequestMapping(value = "/login"  , method=RequestMethod.GET)
	public String goLogin(){
		return "system/login";
	}
}
